﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ShopEnzi.Web.Utils;
using ShopEnzi.Web.Controllers.Api.Requests;
using ShopEnzi.Data.Entities;
using NH.Beng.Dynamic;

namespace ShopEnzi.Web.Controllers.Api
{
    public class ManageApiController : BaseApiController
    {
        [HttpPost]
        [HttpGet]
        public HttpResponseMessage ProductUpdate()
        {
            var xmlurl = "http://api.gelirortaklari.com/dynamic?key=dfbc92d53fe1cdefa8d7d41fbc76359e5484&page=1&count=1000";
            string xmlString = "";
            using (WebClient client = new WebClient())
            {
                xmlString = client.DownloadString(xmlurl);
            }

            var c = XmlHelper.DeSerializeObject<products>(xmlString).GetProducts();

            return Request.CreateResponse(HttpStatusCode.OK, new { }, this.GetFormatter());
        }
        [HttpPost]
        [HttpGet]
        public HttpResponseMessage GetList(ListRequest request)
        {
            var repository = Product.GetRepository(base.unitOfWork);
            var resultdata = repository.GetAll()
                .Where(request.search.ToSearchString())
                .OrderBy(request.sort)
                .Select(q =>
                    new
                    {
                        q.Id,
                        q.FirmProductId,
                        q.Title,
                    }
                 ).AsQueryable();
            var total = resultdata.Count();
            var result = resultdata;
            if (request.pageLength > 0)
                result = resultdata
                .Skip(request.page * request.pageLength).Take(request.pageLength);

            var resultResponse = new
            {
                items = result.ToList(),
                totalPage = request.pageLength > 0 ? total / request.pageLength : 0,
                page = request.page,
                pageLength = request.pageLength,
                total = total
            };
            return Request.CreateResponse(HttpStatusCode.OK, resultResponse, this.GetFormatter());
        }
    }
}
